import re
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from apps.users.models import User
from django.http.response import JsonResponse
from utils.response_code import RETCODE
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo.settings import SECRET_KEY


# 区别手机号和用户名
def distinctUsername(username):
    try:
        if re.match(r'^1[3-9]\d{9}$', username):
            user = User.objects.get(mobile=username)
        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None

    return user


# 自定义用户校验，支持多账号登陆
class AuthenticateUser(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = distinctUsername(username)

        if user.check_password(password) or user is not None:
            return user
        else:
            return None


# 发送邮箱用户认证，没有登录返回json数据给前端js
class LoginRequiredJSONMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        return JsonResponse({'code':RETCODE.SESSIONERR,'errmsg':'未登录'})


# 给用户id加密
def email_secret(user_id):
    secrecy = Serializer(secret_key=SECRET_KEY, expires_in=3600)
    dict_data = {
        'user_id': user_id
    }
    str_data = secrecy.dumps(dict_data).decode()
    return 'http://www.meiduo.site:8000/users/checkemail/' + '?token=' + str_data


# 给用户id解密
def email_open(str_data):
    secrecy = Serializer(secret_key=SECRET_KEY, expires_in=3600)
    try:
        dict_data = secrecy.loads(str_data)
        user_id = dict_data.get('user_id')
    except Exception as e:
        user_id = None
    return user_id